package com.scrawler.html.template;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.scrawler.util.FileUtil;
import com.scrawler.util.PathUtil;


public class RegexTest {
	public static void main(String args[]) { 
	String html = "<p class=\"fz16 line24\"><a href=\"http://sports.ifeng.com/lanqiu/nba/rocketsnews/detail_2013_07/28/27998295_0.shtml\" " +
			"target=\"_blank\">欧洲老牌高炮仍想留在<font color=red>NBA</font> 火箭就缺这种类型</a></p>";
    // 简单示例，相当于String html=getHtml(String urlString);
    List resultList = getContext(html);
    for (Iterator iterator = resultList.iterator(); iterator.hasNext();) {
    	String context = (String) iterator.next();
       // System.out.println(context);
    }
}

/**
 * 提取"<title>XXXX</title>"中的文字XXXX
 * @param html 要解析的html文档内容
 * @return 解析结果，可以多次匹配，每次匹配的结果按文档中出现的先后顺序添加进结果List
 */
public static List getContext(String html) {
    List resultList = new ArrayList();
    //Pattern p = Pattern.compile("<p class=\"fz16 line24\"><a.*?href=['|\"]([^'&^\"]*)['|\"][^>]*>(.*?)</a></p>",2 | Pattern.DOTALL);
    Pattern p = Pattern.compile("<p class=\"fz16 line24\"><a.*?href=['|\"]([^'&^\"]*)['|\"][^>]*>(.*?)</a>",2 | Pattern.DOTALL);

    // <h3>.*?<a.*?href=['|\"]([^'&^\"]*)['|\"][^>]*>(.*?)</a>
    // <span class="s_title">[^<]*<[^>]*>(.*?)</span>
    // <div class="atl-info">.*?<a[^>]*>(.*?)</a>
    // <div class="atl-info">.*?<span>.*?<span>(.*?)</span>
    // <div class="atl-info">.*?<span>.*?<span>.*?<span>.*?<span>(.*?)</span>
    // <div class="bbs-content clearfix">(.*?)</div>
    
   //String regex = FileUtil.readFile(PathUtil.getInstance().getBasePath()+"/demoData/regex.txt");
   //Pattern p = Pattern.compile(regex);

    String content = FileUtil.readFile(PathUtil.getInstance().getBasePath()+"/demoData/ifengS.txt");
    System.out.println(content.length());
    content = content.replaceAll("\\s+"," ");
    
    Matcher m = p.matcher(content);//开始编译
    //System.out.println(html);
    //System.out.println(regex);
    
    while (m.find()) {
    	String url = m.group(1);
        resultList.add(url);//获取被匹配的部分
        String title = m.group(2);
        System.out.println("url: "+url);
        System.out.println("title:" + title);
        resultList.add(title);//获取被匹配的部分
        System.out.println(m.groupCount());
    }
    return resultList;
} 
	
	
	
}
